<template>
	<view class="">
		<u-navbar :is-back="true" :custom-back="back" title="安全设置" :border-bottom="true"></u-navbar>
		
		<u-cell-group>
			<u-cell-item title="修改密码" :arrow="true" @click="showChangePasswordModal = true"></u-cell-item>
			<u-cell-item title="修改手机号" :value="phone || '未绑定'" :arrow="true" @click="showChangePhoneModal = true"></u-cell-item>
			<u-cell-item title="绑定邮箱" :value="email || '未绑定'" :arrow="true" @click="showBindEmailModal = true"></u-cell-item>
		</u-cell-group>
		
		<u-toast ref="uToast" />
		
		<!-- 修改密码弹窗 -->
		<u-modal 
			v-model="showChangePasswordModal" 
			title="修改密码" 
			:show-cancel-button="true" 
			@confirm="changePassword"
			@close="resetPasswordForm"
		>
			<view class="modal-content">
				<u-input 
					v-model="passwordForm.oldPassword" 
					placeholder="请输入旧密码" 
					type="password"
					:clearable="true"
					:password-icon="true"
					class="modal-input"
				></u-input>
				<u-input 
					v-model="passwordForm.newPassword" 
					placeholder="请输入新密码（至少6位）" 
					type="password"
					:clearable="true"
					:password-icon="true"
					class="modal-input"
					style="margin-top: 20rpx;"
				></u-input>
				<u-input 
					v-model="passwordForm.confirmPassword" 
					placeholder="请再次输入新密码" 
					type="password"
					:clearable="true"
					:password-icon="true"
					class="modal-input"
					style="margin-top: 20rpx;"
				></u-input>
			</view>
		</u-modal>
		
		<!-- 修改手机号弹窗 -->
		<u-modal 
			v-model="showChangePhoneModal" 
			title="修改手机号" 
			:show-cancel-button="true" 
			@confirm="changePhone"
			@close="resetPhoneForm"
		>
			<view class="modal-content">
				<u-input 
					v-model="phoneForm.newPhone" 
					placeholder="请输入新手机号" 
					type="number"
					maxlength="11"
					:clearable="true"
					class="modal-input"
				></u-input>
				<view class="code-input-wrapper">
					<u-input 
						v-model="phoneForm.authCode" 
						placeholder="请输入验证码" 
						type="number"
						maxlength="6"
						:clearable="true"
						class="modal-input code-input"
					></u-input>
					<u-button 
						type="primary" 
						size="mini" 
						:disabled="phoneCodeCountdown > 0"
						@click="getPhoneCode"
						class="code-button"
					>
						{{ phoneCodeCountdown > 0 ? phoneCodeCountdown + 's' : '获取验证码' }}
					</u-button>
				</view>
			</view>
		</u-modal>
		
		<!-- 绑定邮箱弹窗 -->
		<u-modal 
			v-model="showBindEmailModal" 
			title="绑定邮箱" 
			:show-cancel-button="true" 
			@confirm="bindEmail"
			@close="resetEmailForm"
		>
			<view class="modal-content">
				<u-input 
					v-model="emailForm.email" 
					placeholder="请输入邮箱地址" 
					type="text"
					:clearable="true"
					class="modal-input"
				></u-input>
			</view>
		</u-modal>
	</view>
</template>

<script>
import $api from '../../api/user.js';

export default {
	data() {
		return {
			userId: null,
			phone: '',
			email: '',
			
			// 修改密码相关
			showChangePasswordModal: false,
			passwordForm: {
				oldPassword: '',
				newPassword: '',
				confirmPassword: ''
			},
			
			// 修改手机号相关
			showChangePhoneModal: false,
			phoneForm: {
				newPhone: '',
				authCode: ''
			},
			phoneCodeCountdown: 0,
			phoneCodeTimer: null,
			
			// 绑定邮箱相关
			showBindEmailModal: false,
			emailForm: {
				email: ''
			}
		}
	},
	onLoad() {
		this.loadUserInfo();
	},
	onUnload() {
		// 清理定时器
		if (this.phoneCodeTimer) {
			clearInterval(this.phoneCodeTimer);
		}
	},
	methods: {
		// 加载用户信息
		loadUserInfo() {
			const user = uni.getStorageSync('user');
			if (!user || !user.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return;
			}
			
			this.userId = user.id;
			this.phone = user.phone || '';
			this.email = user.email || '';
		},
		
		// 修改密码
		changePassword() {
			// 验证旧密码
			if (!this.passwordForm.oldPassword || this.passwordForm.oldPassword.trim() === '') {
				this.$refs.uToast.show({
					title: '请输入旧密码',
					type: 'error',
				});
				return;
			}
			
			// 验证新密码
			if (!this.passwordForm.newPassword || this.passwordForm.newPassword.trim() === '') {
				this.$refs.uToast.show({
					title: '请输入新密码',
					type: 'error',
				});
				return;
			}
			
			if (this.passwordForm.newPassword.length < 6) {
				this.$refs.uToast.show({
					title: '新密码至少6位',
					type: 'error',
				});
				return;
			}
			
			// 验证确认密码
			if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
				this.$refs.uToast.show({
					title: '两次输入的密码不一致',
					type: 'error',
				});
				return;
			}
			
			uni.showLoading({
				title: '修改中...'
			});
			
			this.$api.changePassword({
				userId: this.userId,
				oldPassword: this.passwordForm.oldPassword,
				newPassword: this.passwordForm.newPassword
			}).then(res => {
				uni.hideLoading();
				
				if (res.data && res.data.code === 200) {
					this.$refs.uToast.show({
						title: '密码修改成功',
						type: 'success',
					});
					
					// 重置表单
					this.resetPasswordForm();
					
					// 关闭弹窗
					this.showChangePasswordModal = false;
					
					// 提示用户重新登录
					setTimeout(() => {
						uni.showModal({
							title: '提示',
							content: '密码已修改，请重新登录',
							showCancel: false,
							success: () => {
								// 清除登录信息
								uni.removeStorageSync('token');
								uni.removeStorageSync('user');
								// 跳转到登录页
								uni.reLaunch({
									url: '/pages/login/login'
								});
							}
						});
					}, 1500);
				} else {
					this.$refs.uToast.show({
						title: res.data.message || '密码修改失败',
						type: 'error',
					});
				}
			}).catch(err => {
				uni.hideLoading();
				console.error('修改密码失败', err);
				this.$refs.uToast.show({
					title: err.message || '修改密码失败，请重试',
					type: 'error',
				});
			});
		},
		
		// 重置密码表单
		resetPasswordForm() {
			this.passwordForm = {
				oldPassword: '',
				newPassword: '',
				confirmPassword: ''
			};
		},
		
		// 获取手机验证码
		getPhoneCode() {
			if (!this.phoneForm.newPhone || this.phoneForm.newPhone.length !== 11) {
				this.$refs.uToast.show({
					title: '请输入正确的手机号',
					type: 'error',
				});
				return;
			}
			
			if (!this.phoneForm.newPhone.match(/^1[3-9]\d{9}$/)) {
				this.$refs.uToast.show({
					title: '手机号格式不正确',
					type: 'error',
				});
				return;
			}
			
			// 检查是否与当前手机号相同
			if (this.phoneForm.newPhone === this.phone) {
				this.$refs.uToast.show({
					title: '新手机号不能与当前手机号相同',
					type: 'error',
				});
				return;
			}
			
			this.$api.getAuthCode({
				phone: this.phoneForm.newPhone
			}).then(res => {
				if (res.data && res.data.code === 200) {
					this.$refs.uToast.show({
						title: '验证码已发送',
						type: 'success',
					});
					
					// 开始倒计时
					this.startPhoneCodeCountdown();
				} else {
					this.$refs.uToast.show({
						title: res.data.message || '获取验证码失败',
						type: 'error',
					});
				}
			}).catch(err => {
				console.error('获取验证码失败', err);
				this.$refs.uToast.show({
					title: '获取验证码失败，请重试',
					type: 'error',
				});
			});
		},
		
		// 开始手机验证码倒计时
		startPhoneCodeCountdown() {
			this.phoneCodeCountdown = 60;
			if (this.phoneCodeTimer) {
				clearInterval(this.phoneCodeTimer);
			}
			this.phoneCodeTimer = setInterval(() => {
				if (this.phoneCodeCountdown > 0) {
					this.phoneCodeCountdown--;
				} else {
					clearInterval(this.phoneCodeTimer);
					this.phoneCodeTimer = null;
				}
			}, 1000);
		},
		
		// 修改手机号
		changePhone() {
			// 验证手机号
			if (!this.phoneForm.newPhone || this.phoneForm.newPhone.length !== 11) {
				this.$refs.uToast.show({
					title: '请输入正确的手机号',
					type: 'error',
				});
				return;
			}
			
			if (!this.phoneForm.newPhone.match(/^1[3-9]\d{9}$/)) {
				this.$refs.uToast.show({
					title: '手机号格式不正确',
					type: 'error',
				});
				return;
			}
			
			// 检查是否与当前手机号相同
			if (this.phoneForm.newPhone === this.phone) {
				this.$refs.uToast.show({
					title: '新手机号不能与当前手机号相同',
					type: 'error',
				});
				return;
			}
			
			// 验证验证码
			if (!this.phoneForm.authCode || this.phoneForm.authCode.length !== 6) {
				this.$refs.uToast.show({
					title: '请输入6位验证码',
					type: 'error',
				});
				return;
			}
			
			uni.showLoading({
				title: '修改中...'
			});
			
			this.$api.changePhone({
				userId: this.userId,
				newPhone: this.phoneForm.newPhone,
				authCode: this.phoneForm.authCode
			}).then(res => {
				uni.hideLoading();
				
				if (res.data && res.data.code === 200) {
					const updatedUser = res.data.data;
					
					// 更新本地数据
					this.phone = updatedUser.phone || '';
					
					// 更新本地存储
					const user = uni.getStorageSync('user');
					if (user) {
						user.phone = updatedUser.phone;
						uni.setStorageSync('user', user);
					}
					
					// 重置表单
					this.resetPhoneForm();
					
					// 关闭弹窗
					this.showChangePhoneModal = false;
					
					this.$refs.uToast.show({
						title: '手机号修改成功',
						type: 'success',
					});
				} else {
					this.$refs.uToast.show({
						title: res.data.message || '手机号修改失败',
						type: 'error',
					});
				}
			}).catch(err => {
				uni.hideLoading();
				console.error('修改手机号失败', err);
				this.$refs.uToast.show({
					title: err.message || '修改手机号失败，请重试',
					type: 'error',
				});
			});
		},
		
		// 重置手机号表单
		resetPhoneForm() {
			this.phoneForm = {
				newPhone: '',
				authCode: ''
			};
			if (this.phoneCodeTimer) {
				clearInterval(this.phoneCodeTimer);
				this.phoneCodeTimer = null;
			}
			this.phoneCodeCountdown = 0;
		},
		
		// 绑定邮箱
		bindEmail() {
			// 验证邮箱
			if (!this.emailForm.email || this.emailForm.email.trim() === '') {
				this.$refs.uToast.show({
					title: '请输入邮箱地址',
					type: 'error',
				});
				return;
			}
			
			// 简单的邮箱格式验证
			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			if (!emailRegex.test(this.emailForm.email.trim())) {
				this.$refs.uToast.show({
					title: '邮箱格式不正确',
					type: 'error',
				});
				return;
			}
			
			// 使用更新用户信息接口
			uni.showLoading({
				title: '绑定中...'
			});
			
			this.$api.updateUserInfo({
				userId: this.userId,
				email: this.emailForm.email.trim()
			}).then(res => {
				uni.hideLoading();
				
				if (res.data && res.data.code === 200) {
					const updatedUser = res.data.data;
					
					// 更新本地数据
					this.email = updatedUser.email || '';
					
					// 更新本地存储
					const user = uni.getStorageSync('user');
					if (user) {
						user.email = updatedUser.email;
						uni.setStorageSync('user', user);
					}
					
					// 重置表单
					this.resetEmailForm();
					
					// 关闭弹窗
					this.showBindEmailModal = false;
					
					this.$refs.uToast.show({
						title: '邮箱绑定成功',
						type: 'success',
					});
				} else {
					this.$refs.uToast.show({
						title: res.data.message || '邮箱绑定失败',
						type: 'error',
					});
				}
			}).catch(err => {
				uni.hideLoading();
				console.error('绑定邮箱失败', err);
				this.$refs.uToast.show({
					title: '绑定邮箱失败，请重试',
					type: 'error',
				});
			});
		},
		
		// 重置邮箱表单
		resetEmailForm() {
			this.emailForm = {
				email: ''
			};
		},
		
		back() {
			// 返回到设置界面
			uni.navigateBack({
				delta: 1
			});
		},
	}
}
</script>

<style lang="scss" scoped>
page {
	background-color: #fff;
}

.modal-content {
	padding: 20rpx;
}

.modal-input {
	margin-bottom: 20rpx;
}

.code-input-wrapper {
	display: flex;
	align-items: center;
	margin-top: 20rpx;
	
	.code-input {
		flex: 1;
		margin-right: 20rpx;
		margin-bottom: 0;
	}
	
	.code-button {
		width: 180rpx;
		flex-shrink: 0;
	}
}
</style>

